package cn.edu.nju.askinginhand.activity;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.nju.askinginhand.util.MyAudioRecorder;

/**
 * 
 * @author ZhangZu
 * 
 */
public class AudioQuesActivity extends Activity {
	// record panel widgets
	private Button recordBtn = null;
	private Button previewBtn = null;
	private TextView recordStatusText = null;

	
	private SeekBar previewSeekBar = null;
	private MediaPlayer player = null;
	private MyAudioRecorder recorder;
	private File recordFile = null;
	private Timer mTimer;
	private TimerTask mTimerTask;
	private boolean isChanging = false;
	
	// problem panel widgets
	private View problemPanel;
	private EditText titleEdit = null;
	private Spinner firstSpinner = null;
	private Spinner secondSpinner = null;
	private Button publishBtn = null;
	//private CheckBox autoDetectBox = null;

	private int status = 0;// 0:ready 1:recording 2:stop
	private String[] statusTexts = { "准备就绪", "录制中...", "录制完成" };
	private String[] buttonTexts = { "录制", "停止", "重新录制" };
	private int[] visibles = { View.INVISIBLE, View.INVISIBLE, View.VISIBLE };
	
	private final static String[] class1 = { "不分类", "山东", "江苏" };
	private final static String[][] class2 = { 
			{}, 
			{ "不分类","青岛", "济南" },
			{ "不分类","南京", "无锡" } 
	};

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.audio_ques);
		recordBtn = (Button) findViewById(R.id.recordBtn);
		previewBtn = (Button) findViewById(R.id.previewBtn);
		recordStatusText = (TextView) findViewById(R.id.recordStatusText);
		previewSeekBar = (SeekBar) findViewById(R.id.previewSeekBar);
		previewSeekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
		problemPanel = (RelativeLayout) findViewById(R.id.problemPanel);
		publishBtn = (Button) findViewById(R.id.publishBtn);
		titleEdit = (EditText) findViewById(R.id.titleEdit);
		firstSpinner = (Spinner) findViewById(R.id.firstSpinner);
		secondSpinner = (Spinner) findViewById(R.id.secondSpinner);
		//autoDetectBox = (CheckBox) findViewById(R.id.autoDetectBox);

		initRecordBtn();
		initPreviewBtn();
		initPublishBtn();
		updateAllWidgets();
	}

	public void initRecordBtn() {
		recordBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(recorder == null) {
					recorder = new MyAudioRecorder();
				}
				if (status != 1) {
					status = 1;
					recorder.startRecord();
					// TODO: startRecording //new thread?
				} else {
					// TODO: endRecording & save record
					recorder.stopRecord();
					recordFile = recorder.getFile(); //get the saved file
					Toast.makeText(AudioQuesActivity.this, "音频文件临时保存在"+recordFile.getAbsolutePath(),
							Toast.LENGTH_SHORT).show();
					status = 2;
				}
				updateAllWidgets();
			}
		});
	}

	public void initPreviewBtn() {

		previewBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//player.reset();// 
				Uri uri = Uri.fromFile(recordFile); //
				if(uri==null)//no record
					return;
				player = new MediaPlayer();
				player = MediaPlayer.create(AudioQuesActivity.this,uri);
				initMediaPlayer();
				previewSeekBar.setMax(player.getDuration());//SeekBar
				try {
					player.prepare(); //
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				player.start(); //
			}
		});
	}

	public void initMediaPlayer() {

		player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				Toast.makeText(AudioQuesActivity.this, "播放结束", 1000).show();
				mTimer.cancel();
				player.release();
			}
		});

		// 控制进度条//
		mTimer = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				if (isChanging == true)
					return;
				previewSeekBar.setProgress(player.getCurrentPosition());
			}
		};
		mTimer.schedule(mTimerTask, 0, 10);
	}

	public void initFirstSpinner() {
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.questype_spinner_item,
				R.id.spinnerText, class1);

		firstSpinner.setAdapter(adapter1);
		firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id) {
				ArrayAdapter<String> adapter2 = null;
				if (position == 0) {
					secondSpinner.setVisibility(View.INVISIBLE);
				} else {
					secondSpinner.setVisibility(View.VISIBLE);
					adapter2 = new ArrayAdapter<String>(AudioQuesActivity.this,
							R.layout.questype_spinner_item, R.id.spinnerText,
							class2[position]);
					secondSpinner.setAdapter(adapter2);
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				secondSpinner.setVisibility(View.INVISIBLE);
			}
		});
	}
	
	public void initPublishBtn() {
		publishBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

/*				if (autoDetectBox.isChecked()) {
					// TODO: autoDetect first
				}*/
				
				String title = titleEdit.getText().toString();
				
				String type = "";
				int pos1 = firstSpinner.getSelectedItemPosition();
				if(pos1 != 0) {
					type = class1[pos1]; 
					int pos2 = secondSpinner.getSelectedItemPosition();
					if(pos2 !=0)
						type +=(" "+ class2[pos1][pos2]);
				}
				/**
				 * TODO: publish the problem.
				 */
			}
		});
	}
	
	public void updateAllWidgets() {
		recordStatusText.setText(statusTexts[status]);
		recordBtn.setText(buttonTexts[status]);
		previewSeekBar.setVisibility(visibles[status]);
		previewBtn.setVisibility(visibles[status]);
		problemPanel.setVisibility(visibles[status]);
	}

	class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {

		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {

		}

		public void onStartTrackingTouch(SeekBar seekBar) {
			isChanging = true;
		}

		public void onStopTrackingTouch(SeekBar seekBar) {
			player.seekTo(seekBar.getProgress());
			isChanging = false;
		}

	}
}
